package com.lagou.common;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class RequestMetrics {

    private static final ConcurrentHashMap<String,Long> COST_TIME_MAP = new ConcurrentHashMap();

    private static final ConcurrentHashMap<String, Metrics> REQUEST_ID_MAP = new ConcurrentHashMap<>();

    private static final RequestMetrics requestMetrics = new RequestMetrics();

    private RequestMetrics(){

    }

    public static RequestMetrics getInstance(){
        return requestMetrics;
    }


    public void addNode(String nettyIp, int nettyPort){
        COST_TIME_MAP.put(nettyIp + ":" + nettyPort, 0L);
    }

    public void remoteNode(String nettyIp, int nettyPort){
        COST_TIME_MAP.remove(nettyIp + ":" + nettyPort);
    }


    public ConcurrentHashMap<String,Long> getMetricMap(){
        return COST_TIME_MAP;
    }

    /**
     * 响应时存入数据，根据requestId 进行耗时统计
     * @param requestId
     */
    public void calculate(String requestId){
        final Metrics metrics = REQUEST_ID_MAP.get(requestId);
        Long cost = System.currentTimeMillis() - metrics.getStart();
        COST_TIME_MAP.put(metrics.getNettyIp() + ":" + metrics.getNettyPort(), cost);
        REQUEST_ID_MAP.remove(requestId);
        System.out.println("============="+requestId+"耗时："+ cost);
    }

    /**
     * 获取所有节点耗时统计
     * @return
     */
    public List<Metrics> getAllInstances(){
        ArrayList<Metrics> result = new ArrayList<>();
        COST_TIME_MAP.forEach((url, along) ->{
            String[] split = url.split(":");
            result.add(new Metrics(split[0],Integer.parseInt(split[1]),along));
        });

        return result;
    }

    public void put(String nettyIp, int nettyPort, String requestId){
        long time = System.currentTimeMillis();
        System.out.println("============="+nettyIp+":"+nettyPort+"###"+requestId+"时间"+time);
        REQUEST_ID_MAP.put(requestId, new Metrics(nettyIp, nettyPort, time));
    }

}
